$(function () {
    var dataSales = [[9, 'Exxon Mobil', '339,938.0', '36,130.0', 11],
        [2, 'Wal-Mart Stores', '315,654.0', '11,231.0', 12],
        [3, 'Royal Dutch Shell', '306,731.0', '25,311.0', 105],
        [4, 'BP', '267,600.0', '22,341.0', 180],
        [5, 'General Motors', '192,604.0', '-10,567.0', 170]];
    var obj = {
        hwrap: false,
        resizable: true,
        rowBorders: false,
        //virtualX: true,
        numberCell: {show: true},
        trackModel: {on: true}, //to turn on the track changes.
        toolbar: {
            items: [
                {
                    type: 'button', icon: 'ui-icon-plus', label: 'New Product', listener:
                        {
                            "click": function (evt, ui) {
                                //append empty row at the end.
                                var rowData = {ProductName: 'new product', UnitPrice: 0.2}; //empty row
                                var rowIndx = $grid.pqGrid("addRow", {rowData: rowData});
                                $grid.pqGrid("goToPage", {rowIndx: rowIndx});
                                $grid.pqGrid("setSelection", null);
                                $grid.pqGrid("setSelection", {rowIndx: rowIndx, dataIndx: 'ProductName'});
                                $grid.pqGrid("editFirstCellInRow", {rowIndx: rowIndx});
                            }
                        }
                },
                {type: 'separator'},
                {
                    type: 'button', icon: 'ui-icon-arrowreturn-1-s', label: 'Undo', cls: 'changes', listener:
                        {
                            "click": function (evt, ui) {
                                $grid.pqGrid("history", {method: 'undo'});
                            }
                        },
                    options: {disabled: true}
                },
                {
                    type: 'button', icon: 'ui-icon-arrowrefresh-1-s', label: 'Redo', listener:
                        {
                            "click": function (evt, ui) {
                                $grid.pqGrid("history", {method: 'redo'});
                            }
                        },
                    options: {disabled: true}
                },
                {
                    type: "<span class='saving'>Saving...</span>"
                }
            ]
        },
        scrollModel: {
            autoFit: true
        },
        //historyModel: {
        //    checkEditableAdd: true
        //},
        //editModel: {
        //    allowInvalid: true,
        //    saveKey: $.ui.keyCode.ENTER
        //},
        //editor: {
        //    select: true
        //},
        title: "<b>auto save</b>",
        /*
        change: function (evt, ui) {

            if (ui.source == 'commit' || ui.source == 'rollback') {
                return;
            }
            console.log(ui);
            var $grid = $(this),
                grid = $grid.pqGrid('getInstance').grid;
            var rowList = ui.rowList,
                addList = [],
                recIndx = grid.option('dataModel').recIndx,
                deleteList = [],
                updateList = [];

            for (var i = 0; i < rowList.length; i++) {
                var obj = rowList[i],
                    rowIndx = obj.rowIndx,
                    newRow = obj.newRow,
                    type = obj.type,
                    rowData = obj.rowData;
                if (type == 'add') {
                    var valid = grid.isValid({ rowData: newRow, allowInvalid: true }).valid;
                    if (valid) {
                        addList.push(newRow);
                    }
                }
                else if (type == 'update') {
                    var valid = grid.isValid({ rowData: rowData, allowInvalid: true }).valid;
                    if (valid) {
                        if (rowData[recIndx] == null) {
                            addList.push(rowData);
                        }
                        //else if (grid.isDirty({rowData: rowData})) {
                        else {
                            updateList.push(rowData);
                        }
                    }
                }
                else if (type == 'delete') {
                    if (rowData[recIndx] != null) {
                        deleteList.push(rowData);
                    }
                }
            }
            if (addList.length || updateList.length || deleteList.length) {
                $.ajax({
                    url: '/pro/products/batch',
                    data: {
                        list: JSON.stringify({
                            updateList: updateList,
                            addList: addList,
                            deleteList: deleteList
                        })
                    },
                    dataType: "json",
                    type: "POST",
                    async: true,
                    beforeSend: function (jqXHR, settings) {
                        $(".saving", $grid).show();
                    },
                    success: function (changes) {
                        //commit the changes.
                        grid.commit({ type: 'add', rows: changes.addList });
                        grid.commit({ type: 'update', rows: changes.updateList });
                        grid.commit({ type: 'delete', rows: changes.deleteList });
                    },
                    complete: function () {
                        $(".saving", $grid).hide();
                    }
                });
            }
        },

        history: function (evt, ui) {
            var $grid = $(this);
            if (ui.canUndo != null) {
                $("button.changes", $grid).button("option", { disabled: !ui.canUndo });
            }
            if (ui.canRedo != null) {
                $("button:contains('Redo')", $grid).button("option", "disabled", !ui.canRedo);
            }
            $("button:contains('Undo')", $grid).button("option", { label: 'Undo (' + ui.num_undo + ')' });
            $("button:contains('Redo')", $grid).button("option", { label: 'Redo (' + ui.num_redo + ')' });
        },
        */
        colModel: [
            {title: "Product ID", dataType: "integer", dataIndx: "ProductID", editable: false, width: 80},
            {
                title: "Product Name", width: 165, dataType: "string", dataIndx: "ProductName",
                validations: [
                    {type: 'minLen', value: 1, msg: "Required"},
                    {type: 'maxLen', value: 40, msg: "length should be <= 40"}
                ]
            },
            {
                title: "Quantity Per Unit", width: 140, dataType: "float", align: "right", dataIndx: "QuantityPerUnit",
                validations: [{type: 'gt', value: 0.5, msg: "should be > 0.5"}],
            },
            {
                title: "Unit Price", width: 100, dataType: "float", align: "right", dataIndx: "UnitPrice",
                validations: [{type: 'gt', value: 0.5, msg: "should be > 0.5"}],
                render: function (ui) {
                    var cellData = ui.cellData;
                    if (cellData != null) {
                        return "$" + parseFloat(ui.cellData).toFixed(2);
                    } else {
                        return "";
                    }
                }
            },
            {
                title: "Units In Stock", width: 100, dataType: "integer", align: "right", dataIndx: "UnitsInStock",
                validations: [{type: 'gte', value: 0, msg: "Required"}]
            }
            /*,
            { title: "Discontinued", width: 100, dataType: "bool", align: "center", dataIndx: "Discontinued",
                editor: { type: "checkbox", subtype: 'triple', style: "margin:3px 5px;" },
                validations: [{ type: 'nonEmpty', msg: "Required"}]
            },
            { title: "", editable: false, minWidth: 83, sortable: false,
                render: function (ui) {
                    return "<button type='button' class='delete_btn'>Delete</button>";
                }
            }*/
        ],

        pageModel: {type: "local", rPP: 100},
        // dataModel: {data:dataSales
        // dataType: "JSON",
        // location: "remote",
        // recIndx: "ProductID",
        // url: "/pro/products/get", //for ASP.NET
        //url: "/pro/products.php", //for PHP
        // getData: function (response) {
        //     return { data: response.data };
        // }
        //},
        //load: function (evt, ui) {
        //    var grid = $(this).pqGrid('getInstance').grid,
        //        data = grid.option('dataModel').dataSales;
        //
        //    grid.isValid({ data: data, allowInvalid: true });
        //},
        //refresh: function () {
        //    $("#grid_editing").find("button.delete_btn").button({ icons: { primary: 'ui-icon-scissors'} })
        //    .unbind("click")
        //   .bind("click", function (evt) {
        //       var $tr = $(this).closest("tr");
        //       var rowIndx = $grid.pqGrid("getRowIndx", { $tr: $tr }).rowIndx;
        //       $grid.pqGrid("deleteRow", { rowIndx: rowIndx });
        //   });
        // }
    };
    obj.dataModel = {data: dataSales};
    $("#grid_editing").pqGrid(obj);
    //var $grid = $("#grid_editing").pqGrid(obj);
});